<?php

namespace App\Service;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Repositories\Menu as Menus;

class Menu
{
    private $request;
    public static function getMenu($userId=null){
        if((int)$userId>0){
            $userId = (int)$userId;
        }else{
            $userId = Auth::id();
        }
        if(!$userId){
            return [];
        }
        $allPermission = Permission::getAllPermission($userId);

        if(!$allPermission) return [];
        return Menus::with(['children'=>function($query) use ($allPermission){
            $query->whereIn('permission',$allPermission)
                ->orderBy('order','asc');
        }])->where('parent_id',0)->whereIn('permission',$allPermission)->orderBy('order','asc')->get();
    }
    /**
     * @param Request $request
     *
     * @return $this|\Illuminate\Database\Eloquent\Builder|static
     */
    public function getPageList(Request $request){
        $this->request = $request;
        $pid = isset($request->pid) && $request->pid ? $request->pid : 0;
        $model = Menus::where('parent_id',$pid);
        $model=$model->paginate($this->request->limit)
            ->toArray();
        return $model;
    }
    public function sortCol($id = [],$sort = 50){
        if($id == []){
        }else{
            if(is_array($id)){
                Menus::whereIn('id',$id)->where('order','<>',$sort)->update(['order'=>$sort]);
            }else{
                Menus::where('id',$id)->where('order','<>',$sort)->update(['order'=>$sort]);

            }
        }
    }

    public function getTopMenus(){
        return Menus::where('parent_id',0)->get();
    }
    /**
     * @param array $id
     */
    public function del($id = []){
        if($id == []){

        }else{
            if(is_array($id)){
                Menus::whereIn('id',$id)->delete();
            }else{
                Menus::where('id',$id)->delete();
            }
            Menus::where('parent_id',$id)->delete();
        }
    }
    /**
     * @param $post
     */
    public function insertOrUpdate($post){
        if(isset($post['id'])){
            $model = Menus::find($post['id']);
            $model->href = $post['href']?$post['href']:'';
        }else{
            $model = new Menus();
            if(isset($post['parent_id'])&&$post['parent_id']!=0){
                $model->href = $post['href']?$post['href']:'/admin/index';
            }else{
                $model->href = $post['href']?$post['href']:'';

            }
        }
        $model->title = $post['title'];
        $model->icon = isset($post['icon'])?$post['icon']:'';
        $model->parent_id = isset($post['parent_id'])?$post['parent_id']:0;
        $model->order = $post['order']?$post['order']:50;
        $model->permission  =   isset($post['permission'])&&$post['permission']?$post['permission']:'';
        $model->save();
    }
}
